package cool.taomu.toolkit.mustache

import com.github.mustachejava.DefaultMustacheFactory
import com.google.common.io.Resources
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.StringWriter
import java.net.URL
import java.nio.charset.Charset
import java.util.Map
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory
import cool.taomu.toolkit.template.ITemplate

class MustacheUtils implements ITemplate{
	val static LOG = LoggerFactory.getLogger(MustacheUtils);

	def mustache(URL url, Map<String, Object> dataModel) {
		var writer = new StringWriter();
		var tmp = File.createTempFile("taomubox_mustache", ".mustache")
		try {
			var mf = new DefaultMustacheFactory();
			LOG.info("mustache 模板路径：{}", url.path);
			var content = Resources.toString(url, Charset.forName("UTF-8"))
			FileUtils.writeStringToFile(tmp, content, "UTF-8")
			try(var reader = new InputStreamReader(new FileInputStream(tmp))) {
				var mustache = mf.compile(reader, tmp.absolutePath);
				mustache.execute(writer, dataModel).flush();
			}
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		} finally {
			tmp.delete;
		}

		return writer;
	}
	
	override execute(String path, Map<String, Object> dataModel) {
		throw new UnsupportedOperationException("TODO: auto-generated method stub")
	}
	
}
